package io.oschina.binv.kapp.framework.widget

import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Environment
import android.os.Parcel
import android.os.Parcelable
import android.provider.MediaStore
import android.widget.ImageView
import com.bumptech.glide.Glide
import io.oschina.binv.kapp.BuildConfig
import io.oschina.binv.kapp.R
import java.io.File;
import kotlin.properties.Delegates



/**
 * Created by xuybin on 2017/9/4.
 */
val  MEDIA_IMAGE=0
val  MEDIA_VIDEO=1
class MediaItem(val originalPath: String,val size: Long=0,val width:Int=0,val height:Int=0,val addTime:Long=0,val mediaType:Int=MEDIA_IMAGE,val longitude:Double=0.0,val latitude:Double=0.0,val duration:Int=0, var  compressPath: String="",var select:Boolean=false): Parcelable{


    constructor(parcel: Parcel) : this(
            parcel.readString(),
            parcel.readLong(),
            parcel.readInt(),
            parcel.readInt(),
            parcel.readLong(),
            parcel.readInt(),
            parcel.readDouble(),
            parcel.readDouble(),
            parcel.readInt(),
            parcel.readString(),
            parcel.readByte() != 0.toByte())

    /** 只要文件的路径相同，就认为是相同的文件  */
    override fun equals(o: Any?): Boolean {
        try {
            val other = o as MediaItem
            return this.originalPath.equals(other.originalPath, ignoreCase = true)
        } catch (e: ClassCastException) {
            e.printStackTrace()
        }

        return super.equals(o)
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(originalPath)
        parcel.writeLong(size)
        parcel.writeInt(width)
        parcel.writeInt(height)
        parcel.writeLong(addTime)
        parcel.writeInt(mediaType)
        parcel.writeDouble(longitude)
        parcel.writeDouble(latitude)
        parcel.writeInt(duration)
        parcel.writeString(compressPath)
        parcel.writeByte(if (select) 1 else 0)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<MediaItem> {
        override fun createFromParcel(parcel: Parcel): MediaItem {
            return MediaItem(parcel)
        }

        override fun newArray(size: Int): Array<MediaItem?> {
            return arrayOfNulls(size)
        }
    }


}

class MediaFolder(val name:String,val path:String,val mediaItems: ArrayList<MediaItem> = arrayListOf()){
    /** 只要文件夹的路径和名字相同，就认为是相同的文件夹  */
    override fun equals(o: Any?): Boolean {
        try {
            val other = o as MediaFolder
            return this.path.equals(other.path, ignoreCase = true) && this.name.equals(other.name, ignoreCase = true)
        } catch (e: ClassCastException) {
            e.printStackTrace()
        }

        return super.equals(o)
    }
}

class MediaPicker private constructor(val context: Context, val storeDir: File,val displayMedia:(mediaItem: MediaItem, mediaView: ImageView)-> Unit){
    init {
        if(!storeDir.exists()) storeDir.mkdirs()
    }
    companion object {
        var instance: MediaPicker by  Delegates.notNull()
        fun initMediaPicker(context: Context
                            , storeDir: File= File(Environment.getExternalStorageDirectory(), "/DCIM/"+ BuildConfig.APPLICATION_ID.substringAfterLast("."))
                            ,displayMedia:(mediaItem: MediaItem, mediaView: ImageView)-> Unit={
                                mediaItem: MediaItem, mediaView: ImageView-> Glide
                                    .with(context)
                                    .load(Uri.fromFile(File(mediaItem.originalPath)))
                                    .placeholder(R.drawable.ic_default_image)
                                    //.thumbnail( 0.1f )
                                    .into(mediaView) }){
            instance=MediaPicker(context,storeDir,displayMedia)
        }
        /**
         * 从数据库中读取图片
         */
        fun getMediaWithMediaFolder(context: Context, uri:Uri?=null, path: String=""): List<MediaFolder> {
            val mediaFolders=mutableListOf<MediaFolder>() //返回的文件夹列表
            if(uri==null && path==""){
                val allImagesAndVideos: ArrayList<MediaItem> = arrayListOf() //所有图片和视频
                val allVideos: ArrayList<MediaItem> = arrayListOf()//所有视频
                getMediaWithMediaFolder(context,MediaStore.Video.Media.EXTERNAL_CONTENT_URI,"").forEach{
                    mediaFolder-> allVideos.addAll(mediaFolder.mediaItems)
                }
               val imageFolders=getMediaWithMediaFolder(context,MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"")
                imageFolders.forEach{
                    mediaFolder->allImagesAndVideos.addAll(mediaFolder.mediaItems);
                }
                //降序排序所有视频
                allVideos.sortByDescending { mediaItem->mediaItem.addTime }
                allImagesAndVideos.addAll(allVideos)
                //降序排序所有图片和视频
                allImagesAndVideos.sortByDescending { mediaItem->mediaItem.addTime }

                //首先添加一条：所有图片和视频
                if (allImagesAndVideos.size > 0) {
                    mediaFolders.add( MediaFolder(context.getResources().getString(R.string.mp_all_images_vidoes),"/",allImagesAndVideos))
                }
                //其次添加二条：所有视频
                if (allVideos.size > 0) {
                    mediaFolders.add(MediaFolder(context.getResources().getString(R.string.mp_all_vidoes),"/",allVideos))
                }
                //添加各个图片文件夹
                mediaFolders.addAll(imageFolders)
            }else{
                var projection by Delegates.notNull<Array<String>>()
                var mediaType by Delegates.notNull<Int>()
                when(uri){
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI,MediaStore.Images.Media.EXTERNAL_CONTENT_URI-> {
                        projection=arrayOf(//查询图片需要的数据列
                                MediaStore.Images.Media.DISPLAY_NAME, //图片的显示名称  aaa.jpg
                                MediaStore.Images.Media.DATA, //图片的真实路径  /storage/emulated/0/pp/downloader/wallpaper/aaa.jpg
                                MediaStore.Images.Media.SIZE, //图片的大小，long型  132492
                                MediaStore.Images.Media.WIDTH, //图片的宽度，int型  1920
                                MediaStore.Images.Media.HEIGHT, //图片的高度，int型  1080
                                MediaStore.Images.Media.MIME_TYPE, //图片的类型     image/jpeg
                                MediaStore.Images.Media.DATE_ADDED,//图片被添加的时间，long型  1450518608
                                MediaStore.Images.Media.LONGITUDE,
                                MediaStore.Images.Media.LATITUDE,
                                MediaStore.Images.ImageColumns.ORIENTATION)
                        mediaType=MEDIA_IMAGE
                    }
                    MediaStore.Video.Media.INTERNAL_CONTENT_URI,MediaStore.Video.Media.EXTERNAL_CONTENT_URI-> {
                        projection=arrayOf(
                                MediaStore.Video.Media.DISPLAY_NAME, //图片的显示名称  aaa.jpg
                                MediaStore.Video.Media.DATA, //图片的真实路径  /storage/emulated/0/pp/downloader/wallpaper/aaa.jpg
                                MediaStore.Video.Media.SIZE, //图片的大小，long型  132492
                                MediaStore.Video.Media.WIDTH, //图片的宽度，int型  1920
                                MediaStore.Video.Media.HEIGHT, //图片的高度，int型  1080
                                MediaStore.Video.Media.MIME_TYPE, //图片的类型     image/jpeg
                                MediaStore.Video.Media.DATE_ADDED,//图片被添加的时间，long型  1450518608
                                MediaStore.Video.Media.LONGITUDE,
                                MediaStore.Video.Media.LATITUDE,
                                MediaStore.Video.Media.DURATION)
                        mediaType=MEDIA_VIDEO
                    }
                    else-> {
                        return mediaFolders
                    }
                }
                var cursor by Delegates.notNull<Cursor>()
                if(path.isEmpty()){
                    cursor=context.applicationContext.contentResolver.query(uri, projection, null, null, projection[6] + " DESC")
                }else{
                    cursor=context.applicationContext.contentResolver.query(uri, projection, projection[1] + " like '%" + path + "%'", null, projection[6] + " DESC")
                }
                while (cursor.moveToNext()) {
                    //查询数据
                    //val imageName = cursor.getString(cursor.getColumnIndexOrThrow(projection[0]))
                    val imagePath = cursor.getString(cursor.getColumnIndexOrThrow(projection[1]))

                    val file = File(imagePath)
                    if (!file.exists() || file.length() <= 0) {
                        continue
                    }
                    val imageSize = cursor.getLong(cursor.getColumnIndexOrThrow(projection[2]))
                    val imageWidth = cursor.getInt(cursor.getColumnIndexOrThrow(projection[3]))
                    val imageHeight = cursor.getInt(cursor.getColumnIndexOrThrow(projection[4]))
                    //val imageMimeType = cursor.getString(cursor.getColumnIndexOrThrow(projection[5]))
                    val imageAddTime = cursor.getLong(cursor.getColumnIndexOrThrow(projection[6]))
                    val longitude = cursor.getDouble(cursor.getColumnIndexOrThrow(projection[7]))
                    val latitude = cursor.getDouble(cursor.getColumnIndexOrThrow(projection[8]))
//                    var duration= ExifInterface.ORIENTATION_UNDEFINED
//                    when(uri){
//                        MediaStore.Video.Media.INTERNAL_CONTENT_URI,MediaStore.Video.Media.EXTERNAL_CONTENT_URI->duration=cursor.getInt(cursor.getColumnIndexOrThrow(projection[9]))
//                    }
                    var duration=cursor.getInt(cursor.getColumnIndexOrThrow(projection[9]))
                    //封装实体
                    val imageItem = MediaItem(imagePath,imageSize,imageWidth,imageHeight,imageAddTime,mediaType,longitude,latitude,duration)
                    //根据父路径分类存放图片
                    val imageFile = File(imagePath)
                    val imageParentFile = imageFile.getParentFile()
                    val imageFolder = MediaFolder(imageParentFile.getName(),imageParentFile.getAbsolutePath())
                    if (!mediaFolders.contains(imageFolder)) {
                        //新文件夹
                        imageFolder.mediaItems.add(imageItem)
                        mediaFolders.add(imageFolder)
                    } else {
                        mediaFolders.get(mediaFolders.indexOf(imageFolder)).mediaItems.add(imageItem)
                    }
                }
                if (cursor != null && !cursor.isClosed) cursor.close()
            }
            return mediaFolders.toList()
        }
    }
}

data class  SelectItemsEvent(val selectItems: java.util.ArrayList<MediaItem>)